# -*- coding: utf-8 -*- 
import threading,  Queue
import time
import select
import sys
import socket
import string
from generic import *
from window_chat import *

class SendRecv():
    def __init__(self,  q,  queueSend):
        client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            client_sock.connect(("127.0.0.1",  8000))
        except:
            try:
                client_sock.connect(("127.0.0.1",  8001))
                print "Se ha conectado al puerto 8001"
            except:
                print "No se ha podido conectar a ningun servidor"
        self.text = ""
        
        try:
            _continue = 1
            while _continue:
                (sread, swrite, sexc) = select.select([0, client_sock],  [], [],  1)
                try:
                    send_true = q.get(True,  1)
                    if send_true == 2:
                        _continue = 0
                    else:
                        send_text = q.get(True,  1)
                        client_sock.send(send_text)
                except:
                    send_text = ''
                for sock in sread :
                    msg = client_sock.recv(1024)
                    msg = msg.split()
                    msg = " ".join(msg[1:])
#                    print "\nEl server envio el mensaje: ",  msg
                    queueSend.put(1)
                    queueSend.put(msg)
        except:
            print "No se pudo hacer nada"

        client_sock.close()
        print "Terminó SendRecv"
